package com.rapid.maintenance.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.text.HtmlCompat;

import com.rapid.maintenance.R;

import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;

/**
 *
 */
public class AttributeTextView extends AppCompatTextView {
    String title;
    String titleColor;
    int divider;

    public AttributeTextView(Context context) {
        this(context, null);
    }

    public AttributeTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AttributeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.AttributeTextView, defStyleAttr, 0);
        title = a.getString(R.styleable.AttributeTextView_attribute_title);
        titleColor = a.getString(R.styleable.AttributeTextView_attribute_title_color);
        divider = a.getInt(R.styleable.AttributeTextView_attribute_title_divider, -1);

        a.recycle();
        setText(getText());
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);

        if (title != null && !text.toString().startsWith(title)) {
            if (divider == 0)
                setText(HtmlCompat.fromHtml("<font color= '" + titleColor + "'>" + title + "：</font>" + text, FROM_HTML_MODE_LEGACY));
            else if (divider == 1)
                setText(HtmlCompat.fromHtml("<font color= '" + titleColor + "'>" + title + "</font><br>" + text, FROM_HTML_MODE_LEGACY));
            else if (divider == 2) {
                setText(HtmlCompat.fromHtml("<font color= '" + titleColor + "'>" + title + "</font> " + text, FROM_HTML_MODE_LEGACY));
            }
        }
    }
}
